'use client'

import { signIn } from 'next-auth/react'
import { useState } from 'react'

export default function TestLoginForm() {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const handleTestLogin = async () => {
    setLoading(true)
    setError('')
    try {
      // 从URL获取callbackUrl
      const url = new URL(window.location.href);
      const callbackUrl = url.searchParams.get('callbackUrl') || '/ty/zh/profile';

      const result = await signIn('credentials', {
        username: 'test',
        password: 'test',
        redirect: false,
        callbackUrl: callbackUrl
      })

      if (result?.error) {
        setError('登录失败：' + result.error)
      } else if (result?.url) {
        window.location.href = result.url
      }
    } catch (error) {
      console.error('登录失败:', error)
      setError('登录过程发生错误')
    } finally {
      setLoading(false)
    }
  }

  // 仅在开发环境显示测试登录按钮
  if (!process.env.NEXT_PUBLIC_ENABLE_TEST_AUTH) {
    return null
  }

  return (
    <div className="mt-4 w-full">
      {error && (
        <div className="text-red-500 mb-4 text-center text-sm">
          {error}
        </div>
      )}
      <button
        onClick={handleTestLogin}
        disabled={loading}
        className="w-full bg-gray-500 text-white py-2 px-4 rounded-lg hover:bg-gray-600 disabled:opacity-50 transition-colors duration-200"
      >
        {loading ? '登录中...' : '使用测试账号登录'}
      </button>
    </div>
  )
}